package util.security;

/**
 * 使用MD5实现的数据hash加密
 */
import java.util.*;

public class WebServicePostValidate {
	private final String syskey = SystemParameter.key;

	/***
	 * 通过在TreeMap中的参数和用户ak，以及系统sysKey返回一个加密的hash码，这个主要给用户请求时进行身份验证
	 * @param dic
	 * @param ak
	 * @return hash码
	 */
	//备注：唯一码ak可以采用java.util.UUID.randomUUID()来获取
    public String encipheringSign(TreeMap<String, String> dic, String ak)
    {
        String sign = EnCriptUtil.getEcriptStr(sortDictionaryByKeyToStr(dic) + ak + syskey,"MD5");
        return sign;
    }
    
    /***
	 * 通过在TreeMap中的参数和用户ak返回一个加密的hash码，这个主要给用户密码进行加密
	 * @param dic
	 * @param ak
	 * @return hash码
	 */
    public String encipheringSign(TreeMap<String, String> dic)
    {
        String sign = EnCriptUtil.getEcriptStr(sortDictionaryByKeyToStr(dic) + syskey,"MD5");
        return sign;
    }

    private String sortDictionaryByKeyToStr(TreeMap<String, String> dic)
    {
        if (dic == null || dic.size() < 1)
        {
            return null;
        }
        String parasStr = "";
        Set<String> keySet = dic.keySet(); 
        Iterator<String> iter = keySet.iterator(); 
        if(iter.hasNext()){
        	String key = iter.next(); 
        	parasStr += key + "=" + dic.get(key).toString();
        }
        	
        while(iter.hasNext()){ 
        	String key = iter.next(); 
        	parasStr += "&" + key + "=" + dic.get(key).toString();
        }

        return parasStr;
    }
    
    public static void main(String args[]){
    	WebServicePostValidate server = new WebServicePostValidate();
    	TreeMap<String,String> dic = new TreeMap<String,String>();
    	dic.put("id", "195");
    	dic.put("name", "zhangjs");
    	dic.put("sex", "男");
    	dic.put("mobile", "137084674329");
    	String enpStr = server.sortDictionaryByKeyToStr(dic);
    	
    	System.out.println(enpStr);
    	String md5Str = server.encipheringSign(dic, "ecc4e4f5-e4db-4ce9-8320-ff09f55c9ef9");
    	System.out.println(md5Str);
    	//sha-1 88b6624e07645a96389623d209e4ed5f572d10
    	//md5   c0610786f0d031de8f7a0c3abfe6d2
    	if(md5Str.equals("032eb154f3a33949bf2a4e6b263693"))
    		System.out.println("匹配");
    	else
    		System.out.println("不匹配");
    	
    	TreeMap<String,String> dic1 = new TreeMap<String,String>();
    	dic.put("userid", "zhangjs");
    	dic.put("pwd", "123456");
    	String encriptpwd = server.encipheringSign(dic);
    	System.out.println(encriptpwd);
    	
    	
    }
}
